package com.vip.jwt.config;

import com.vip.jwt.common.exception.MyException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author vip
 * @date 2020-5-5 11:28
 * 多Realm认证实现类
 */
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {

    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        //判断getRealms()是否返回为空
        assertRealmsConfigured();
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) authenticationToken;
        JwtToken jwtToken = new JwtToken(token.getUsername());
        String loginType = token.getLoginType();
        Collection<Realm> realms = getRealms();
        //登录类型对应的所有Realm
        List<Realm> realmList = new ArrayList<>();
        for (Realm realm : realms) {
            if (realm.getName().contains(loginType)) {
                realmList.add(realm);
            }
        }
        if(realmList.size()<1)
            throw new MyException("未找到相应Realm,无法认证、授权");
        else if(realmList.size()==1){
            return doSingleRealmAuthentication(realmList.get(0),jwtToken);
        }else{
            return doMultiRealmAuthentication(realmList,jwtToken);
        }
    }

}
